const AJAX = getApp().ajax,
      $wx = getApp().$wx,
      getColor = getApp().globalData.getColor;
// console.log(wx.getLaunchOptionsSync());    //获取小程序启动时的参数

Page({
  data:{
    lazyLoadImg: getApp().globalData.lazyLoadImg,    
    navItem: 0,
    swiperCurrent: 0,
    shopConfig: {},
    goodsList: { data: [] },
    commentNavItem: 0,
    getGoodsListParams: { sell: 2 },
    DeliveryArea: false,
    isSpecification: false,
    shoppingTrolley:  {},
    showCommodityHint: false,
    commoditySpecIndex: 0,
    commentListParams: { type: 0, page: 1},
    ContainerScrollTop: 0
  },

  onLoad(options){
    $wx.setNavColor(getColor().val);
    $wx.setNavBg(getColor().val);

    this.setData({ 
      getColor: getColor()
    });
    this.getShopConfig();
    
  },

  onShow(){
    let _this = this, 
    token = wx.getStorageSync('token');
    
    if (token.length > 0){
      setTimeout(callback => {
        _this.getCarList();
        _this.addScanKey(wx.getStorageSync('sceneInfo').key);
      }, 1000);
    }
  },

  onReady(){
    let _this = this, query = wx.createSelectorQuery();
    query.select('#swiper').boundingClientRect((rect) => {
      let top = rect.top;
      _this.SwiperScrollTop = top;
    }).exec()
  },
  
  onPullDownRefresh(){
  },

  onShareAppMessage(){

  },

  // 扫码
  scanCode(){
    let _this = this;
    wx.scanCode({
      success(res) {
        let url_params = $wx.getUrlParams(res.path);
        wx.setStorageSync('sceneInfo', { key: url_params.scene });
        setTimeout(callback => {
          wx.reLaunch({
            url: '/pages/tab-bar/authorization/authorization'
          });
        },1000);
      },
      fail(error) {
        if (error.errMsg == 'scanCode:fail'){
          $wx.showToast('未能识别！');
        }
      }
    });
  },

  // 获取导航下标
  getNavItem(e){
    let _this = this, td = _this.data, 
        item = parseInt(e.currentTarget.dataset.item);

    if(td.navItem != item){
      _this.setData({
        navItem: item,
        swiperCurrent: item
      });

      switch (item) {
        case 1:
          _this.getCommentList();
          break;
      }
    }
  },

  // swiper改变
  swiperChange(e){
    let _this = this, td = _this.data, 
        current = e.detail.current;

    if (td.navItem != current){
     _this.setData({
       navItem: current,
       swiperCurrent: current
     });

     switch (current) {
       case 1:
         _this.getCommentList();
         break;
     }
   }
  },

  // 评价导航
  commentNavItem(e){
    let _this = this, td = _this.data, 
        item = parseInt(e.currentTarget.dataset.item);

    if (td.commentNavItem != item){
      this.setData({
        commentNavItem: item
      });

      switch (item) {
        case 0:
          td.commentListParams = { type: 0, page: 1 };
          _this.getCommentList();
          break;
        case 1:
          td.commentListParams = { type: 1, page: 1};
          _this.getCommentList();
          break;
      }
    }
  },  

  // 评价上拉
  commentTolower(){
    let td = this.data;
    if (td.commentListParams.page < td.commentList.last_page){
      ++td.commentListParams.page;
      this.getCommentList();      
    }
  },

  // 获取tab-y项
  getTabyItem(e){
    let _this = this, 
        td = _this.data, 
        detail = e.detail;

    td.goodsList.current_page = 1;

    if (detail.index == 0){
      _this.setData({
        getGoodsListParams: { sell: 2 },
        goodsList: { data: [] },
        showCommodityHint: false
      });

    } else if (detail.index == 1){
      _this.setData({
        getGoodsListParams: { discount: 2 },
        goodsList: { data: [] },
        showCommodityHint: false
      });

    }else{
      _this.setData({
        getGoodsListParams: { type_id: detail.params.id },
        goodsList: { data: [] },
        showCommodityHint: false
      });
    }
    _this.getGoodsList();    
  },

  scrollStart(e){
    let touches = e.changedTouches[0];
    // this.ScrollStartTime = e.timeStamp;
    this.ScrollStartY = touches.pageY; 
  },

  scrollEnd(e){
    let td = this.data;
    let touches = e.changedTouches[0];
    // this.ScrollEndTime = e.timeStamp;
    let start_Y = this.ScrollStartY;
    let end_Y = touches.pageY;
    let swiper_scroll_top = this.SwiperScrollTop;
    
    if (start_Y > end_Y) {
      if (td.ContainerScrollTop < swiper_scroll_top){
        this.setData({ ContainerScrollTop: swiper_scroll_top });
      }
    } else if (start_Y < end_Y){
      td.ContainerScrollTop = 0;
    }
  },

  // 商品（上拉加载更多）
  commodityTolower(e){
    let _this = this, td = _this.data, 
        current_page = e.currentTarget.dataset.page;
        
    if (td.goodsList.current_page < td.goodsList.last_page){
      td.getGoodsListParams.p = ++td.goodsList.current_page;
      _this.getGoodsList();
    }else{
      _this.setData({ showCommodityHint: true });
    }
  },

  // 减少购物车数量
  inputNumSubtract(e){
    let params = e.detail.params;

    this.EditCar(params.id, {
      goods_id: params.id,
      attr_id: params.attr_id || 0,
      num: --params.car_num
    }); 
  },

  // 增加购物车数量
  inputNumAdd(e){
    let params = e.detail.params;

    this.EditCar(params.id, {
      goods_id: params.id,
      attr_id: params.attr_id || 0,
      num: ++ params.car_num
    });
  }, 

  // 减少购物车列表数量
  inputNumSubtract2(e) {
    let params = e.detail.params;

    this.EditCar(params.goods_id, {
      goods_id: params.goods_id,
      attr_id: params.attr_id || 0,
      num: --params.car_num
    });
  },

  // 增加购物车列表数量
  inputNumAdd2(e) {
    let params = e.detail.params;

    this.EditCar(params.goods_id, {
      goods_id: params.goods_id,
      attr_id: params.attr_id || 0,
      num: ++params.car_num
    });
  }, 
  
  // 获取规格
  getSpecification(e){
    let params = e.currentTarget.dataset.params;
    this.getCommoditySpce(params.id);
  },

  // 选择规格
  selectedCommoditySpec(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      commoditySpecIndex: index
    });
  },

  // 增加购物车列表数量
  inputNumAdd3(e){
    let params = e.detail.params;

    this.EditCar(params.goods_id, {
      goods_id: params.goods_id,
      attr_id: params.id,
      num: ++params.car_num
    }, true);
  },

  // 增加购物车列表数量
  inputNumAddBtn(e) {
    let params = e.currentTarget.dataset.params;

    this.EditCar(params.goods_id, {
      goods_id: params.goods_id,
      attr_id: params.id,
      num: ++params.car_num
    }, true);
  }, 

  // 减少购物车列表数量
  inputNumSubtract3(e) {
    let params = e.detail.params;

    this.EditCar(params.goods_id, {
      goods_id: params.goods_id,
      attr_id: params.id,
      num: --params.car_num
    }, true);
  },

  // 取消规格
  cancelSpecification(){
    this.setData({
      isSpecification: false
    });
  },
  
  // 查看商品详情
  viewCommodityDetail(e){
    let commodity_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/other-pages/good-detail/good-detail?goods_id=' + commodity_id,
    });
  },

  // 查看购物车
  viewShoppingTrolley(e){
    let td = this.data, list = e.currentTarget.dataset.list;

    if(list.length > 0){
      this.setData({
        showShoppingTrolley: !td.showShoppingTrolley
      });
    }else{
      $wx.showToast('还没有商品哦~，快去购买商品吧!');
    }
  },

  // 购物车背景(遮罩层)
  shoppingTrolleyBg(e){
    let td = this.data;

    this.setData({
      showShoppingTrolley: !td.showShoppingTrolley
    });
  },

  // 清空购物车
  emptyCart(){
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '确定要清空购物车吗？',
      success(resModal){
        if(resModal.confirm){
          _this.deleteCar({
            is_all_id: 1
          });
        }
      }
    })
  },

  // 提交订单
  submitOrder(e){
    let status = e.currentTarget.dataset.status;

    if(status){
      wx.navigateTo({
        url: '/pages/other-pages/submit-order/submit-order'
      })
    }
  },

  // 打电话
  ringUp(e){
    let num = e.currentTarget.dataset.num;

    wx.makePhoneCall({ phoneNumber: num });
  },

  // 查看商家资质
  viewShopsInformation(e){
    let imgs = JSON.stringify(e.currentTarget.dataset.imgs);
    
    wx.navigateTo({
      url: '/pages/other-pages/shops-information/shops-information?shops_information_img=' + imgs
    });
  },
  
  // 预览评论图片
  viewCommentImg(e) {
    let index = e.currentTarget.dataset.index,
      imgs = e.currentTarget.dataset.imgs;

    wx.previewImage({
      current: imgs[index],
      urls: imgs,
      fail(res) {
        $wx.showToast(res.msg);
      }
    });
  },

  // 预览商家图片
  viewShopImg(e){
    let index = e.currentTarget.dataset.index,
        imgs = e.currentTarget.dataset.imgs,
        preview_imgs = [];

    imgs.forEach(item => {
      preview_imgs.push(item.image);
    });

    wx.previewImage({
      current: preview_imgs[index],
      urls: preview_imgs,
      fail(res) {
        $wx.showToast(res.msg);
      }
    });
  },

  // 获取扫码记录
  getScanRecord(e){
    let td = this.data, index = e.detail.value;
    let scan_record_key = td.scanRecord[index].key;
    let key = wx.getStorageSync('sceneInfo').key;

    if (key !== scan_record_key){
      wx.setStorageSync('sceneInfo', { key: scan_record_key });
      setTimeout(callback => {
        wx.reLaunch({
          url: '/pages/tab-bar/authorization/authorization'
        });
      }, 1000);
    }else{
      $wx.showToast('已经是当前店铺啦 ~');
    }
  },

  /**
   * 商店配置
   * */
  getShopConfig(refresh){
    let _this = this;
    wx.showNavigationBarLoading();
    
    AJAX.getShopConfig({}, (status, data, msg) => {
      wx.hideNavigationBarLoading();

      if (status) {
        if (data) {
          data.goodsType.unshift(
            {
              icon: '/imgs/dp_xd_ico_rx.png',
              selectedIconSrc: '/imgs/dp_xd_ico_rx.png',
              type_name: '热销'
            },
            {
              icon: '/imgs/dp_ico_zk.png',
              selectedIconSrc: '/imgs/dp_ico_zk.png',
              type_name: '折扣'
            }
          );
          wx.setNavigationBarTitle({ title: data.shop_name });
          wx.setStorageSync('shopConfig', data);

          _this.setData({
            shopConfig: data,
            DeliveryArea: data.is_true == 2 ? true : false
          });

          wx.getImageInfo({
            src: data.img,
            success(res){
              let img_width = res.width, img_height = res.height;
              let img_scale = img_width / img_height;
              _this.setData({
                imgScale: img_scale
              });
            }
          })

          if (!refresh) {
            _this.getGoodsList();
          }
          _this.submitStatus();
          
        } else {
          _this.setData({
            shopConfig: {}
          });
        }
      } else {
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 列表
   * @param sell      当值为2时,为热销查询
   * @param discount  当值为2时,为折扣查询
   * @param $type_id  商品分类id
   * @param p  	      当前请求页数 默认为1
   * @param num  	    每页请求条数 默认值为10
   * */
  getGoodsList(){
    let _this = this, td = _this.data;
    wx.showLoading({
      title: '加载中...'
    });

    AJAX.getGoodsList(td.getGoodsListParams, (status, data, msg) => {
      wx.hideLoading();
      if (status) {
        let gld = td.goodsList.data.concat(data.data);
        td.goodsList = data;
        td.goodsList.data = gld;
        _this.setData({ goodsList: td.goodsList });
      } else {
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 获取商品规格
   * @param goods_id
   * */ 
  getCommoditySpce(goodsId){
    let _this =  this;
    wx.showLoading({
      title: '加载中...',
    });

    AJAX.getCommoditySpce({
      goods_id: goodsId 
    },(status, data, msg)=>{
      wx.hideLoading();
      if(status){
        _this.setData({
          isSpecification: true,
          commoditySpce: data
        });
      }else{
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 修改购物车
   * @param goods_id
   * @param attr_id
   * @param num
   * */
  EditCar(goodsId, params = {}, isCommoditySpce){
    let _this = this, td = _this.data;
    wx.showLoading({
      title: '加载中...'
    });

    AJAX.editCar(params,(status, data, msg)=>{
      wx.hideLoading();

      if(status){
        let gl = td.goodsList;
        gl.data.forEach((item, index)=>{
          if (gl.data[index].id == goodsId) {
            gl.data[index].car_num = data.car_num;
          }
        });

        _this.setData({ goodsList: gl });
        _this.getCarList();

        if (isCommoditySpce){
          _this.getCommoditySpce(goodsId);
        }

      }else{
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 购物车列表
   * */
  getCarList() {
    let _this = this, td = _this.data,
        gl = td.goodsList;

    AJAX.getCarList({}, (status, data, msg) => {
      if (status) {
        _this.setData({
          shoppingTrolley: data
        });

        if (!data.data || data.data.length == 0){
          if (gl.data.length > 0){
             gl.data.forEach((item, index) => {
               gl.data[index].car_num = 0;
             });

             _this.setData({
               goodsList: gl
             });
           }
           
          _this.setData({
            showShoppingTrolley: false
          });
        }
        _this.submitStatus();
      } else {
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 删除购物车
   * @param id 
   * @param is_all_id =1 为全部删除
   * */
  deleteCar(params) {
    let _this = this;
   
    AJAX.deleteCar(params, (status, data, msg) => {
      if (status) {
        console.log('删除购物车:',data);
        _this.getCarList();
        
      } else {
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 提交状态
   * */ 
  submitStatus(){
    let _this = this, td = _this.data,
        shopConfig = td.shopConfig,
        shoppingTrolley = td.shoppingTrolley;
    
    if (shoppingTrolley.totalPrice && shopConfig.start_price){
      let total_price = parseFloat(shoppingTrolley.totalPrice),
          start_price = parseFloat(shopConfig.start_price);

      if (total_price >= start_price) {
        _this.setData({
          submitOrderInfo: '去结算'
        });

      } else if (total_price > 0 && total_price < start_price) {
        let price = Math.abs((total_price - start_price).toFixed(2));
        _this.setData({
          submitOrderInfo: `还差￥${price}元`
        });
        
      }
    } else if (!shoppingTrolley.totalPrice) {
      _this.setData({
        submitOrderInfo: `￥${shopConfig.start_price || 0}元起`
      });
    }
  },

  /**
   * 评论列表
   * @param type
   * */ 
  getCommentList(){
    let _this = this, td = _this.data;
    wx.showLoading({
      title: '加载中...'
    });

    AJAX.commentList(td.commentListParams,(status, data, msg)=>{
      wx.hideLoading();
      if(status){
        _this.setData({
          commentList: data
        });
      }else{
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 增加扫码记录
   * @param key
   * */ 
  addScanKey(key){
    let _this = this;
    AJAX.addScanKey({key}, (status, data, msg) => {
      // if(status){
      //   _this.getScanKey();
      // }
    });
  },

  /**
   * 获取扫码记录
   * @param p
   * @param num
   * */ 
  getScanKey(params = {}){
    let _this = this;
    AJAX.getScanKey(params, (status, data, msg) => {
      if(status){
        _this.setData({
          scanRecord: data
        });
      }
    });
  }
});